<template>
  <XenListPage
    title="调岗调薪"
    :dataList="transferList"
    :visibleFields="visibleFields"
    :filterFields="filterFields"
    :actions="actions"
    :themeConfig="themeConfig"
    :loading="loading"
    :enableAutoRefresh="false"
    :enableSilentRefresh="true"
    :silentRefreshFn="silentRefreshFn"
    searchPlaceholder="点击筛选调岗调薪信息"
    emptyText="暂无调岗调薪信息"
    emptyDesc="点击右上角添加调岗调薪"
    createPagePath="/subpkg-hr-syshrtransferrequestbill/create"
    detailPagePath="/subpkg-hr-syshrtransferrequestbill/details"
    editPagePath="/subpkg-hr-syshrtransferrequestbill/edit"
    permission-module="SysHrTransferRequestBill"
    @delete="handleDelete"
    @filter="handleFilter"
    @refresh="handleRefresh"
    @silent-refresh="handleSilentRefresh"
  >
    <!-- 自定义插槽图标 -->
    <template #search-icon>
      <uni-icons type="search" size="18" color="#999"></uni-icons>
    </template>
    <template #add-icon>
      <uni-icons type="plus" size="18" color="#ffffff"></uni-icons>
    </template>
    <template #loading-icon>
      <uni-icons type="spinner-cycle" size="24" color="#666"></uni-icons>
    </template>
    <template #empty-icon>
      <uni-icons type="info" size="48" color="#ccc"></uni-icons>
    </template>
    <template #action-icon-delete>
      <uni-icons type="trash" size="16" color="#FF5252"></uni-icons>
    </template>
    <template #action-icon-edit>
      <uni-icons type="compose" size="16" color="#4CAF50"></uni-icons>
    </template>
    <template #action-icon-view>
      <uni-icons type="eye" size="16" color="#7881de"></uni-icons>
    </template>
  </XenListPage>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import XenListPage from "@/layouts/XenListPage.vue";
import SysHrTransferRequestBillApi from "./api/index";
import commonApi from "@/api/common";
import { processDateRangeField } from "@/utils/dateRangeUtils";
import { formatDateTime } from "@/utils/xenUtils";
import type {
  ISysHrTransferRequestBillView,
  ISysHrTransferRequestBillQuery,
} from "./api/interface";

// 创建API实例
const api = SysHrTransferRequestBillApi();
const commonApiInstance = commonApi();

// 主题配置
const themeConfig = {
  primaryColor: "#7881de",
  secondaryColor: "#764ba2",
  gradientStart: "#667eea",
  gradientEnd: "#764ba2",
};

// 定义列表显示字段（按优先级排列）
const visibleFields = [
  {
    key: "Name",
    label: "员工",
    formatter: (value: any) => value || "",
  },
  {
    key: "WorkflowStatus",
    label: "工作流状态",
    type: "badge",
    formatter: (value: any) => value || "",
    badgeConfig: {
      colorMap: {
        待提交: "gray",
        提交中: "blue",
        审核中: "orange",
        已完成: "green",
        已取消: "red",
      },
      defaultColor: "gray",
      prefix: "badge-",
    },
  },
  {
    key: "BillStatus",
    label: "单据状态",
    formatter: (value: any) => {
      if (value === 0 || value === "草稿") return "草稿";
      if (value === 1 || value === "正文") return "正文";
      return value || "";
    },
  },
  {
    key: "GroupName",
    label: "所属部门",
    formatter: (value: any) => value || "",
  },
  {
    key: "OriginalGroupName",
    label: "原部门",
    formatter: (value: any) => value || "",
  },
  {
    key: "NewGroupName",
    label: "新部门",
    formatter: (value: any) => value || "",
  },
  {
    key: "OriginalPositionName",
    label: "原岗位",
    formatter: (value: any) => value || "",
  },
  {
    key: "NewPositionName",
    label: "新岗位",
    formatter: (value: any) => value || "",
  },
  {
    key: "OriginalBaseSalary",
    label: "原基本薪资",
    formatter: (value: any) => value || "",
  },
  {
    key: "NewBaseSalary",
    label: "新基本薪资",
    formatter: (value: any) => value || "",
  },
  {
    key: "OriginalPositionSalary",
    label: "原岗位薪资",
    formatter: (value: any) => value || "",
  },
  {
    key: "NewPositionSalary",
    label: "新岗位薪资",
    formatter: (value: any) => value || "",
  },
  {
    key: "ApplyDate",
    label: "申请日期",
    formatter: (value: any) => {
      if (!value) return "";
      const formattedDateTime = formatDateTime(value);
      return formattedDateTime ? formattedDateTime.split(" ")[0] : "";
    },
  },
  {
    key: "EffectiveDate",
    label: "生效时间",
    formatter: (value: any) => {
      if (!value) return "";
      const formattedDateTime = formatDateTime(value);
      return formattedDateTime ? formattedDateTime.split(" ")[0] : "";
    },
  },
  {
    key: "Approver",
    label: "审批人",
    formatter: (value: any) => value || "",
  },
  {
    key: "ApprovalTime",
    label: "审批时间",
    formatter: (value: any) => {
      return formatDateTime(value);
    },
  },
  {
    key: "BillCode",
    label: "单据编号",
    formatter: (value: any) => value || "",
  },
  {
    key: "Remark",
    label: "备注",
    formatter: (value: any) => value || "",
  },
  {
    key: "OrgName",
    label: "公司",
    formatter: (value: any) => value || "",
  },
  {
    key: "TransferType",
    label: "调整类型",
    formatter: (value: any) => {
      // 如果后端返回字符串，直接显示
      if (typeof value === "string") {
        return value;
      }
      // 兼容后端可能返回数字的情况
      if (typeof value === "number") {
        const typeTexts = [
          "岗位调整",
          "薪资调整",
          "岗位和薪资调整",
          "晋升",
          "降级",
        ];
        if (value >= 0 && value < typeTexts.length) {
          return typeTexts[value];
        }
      }
      return value || "";
    },
  },
];

// 定义搜索筛选字段
const filterFields: any[] = [
  {
    key: "personId",
    label: "员工",
    type: "autocomplete",
    placeholder: "请输入员工姓名搜索",
    searchApi: async (query: string) => {
      try {
        const isStaffNo = /^\d+$/.test(query.trim());
        const searchParams: any = {
          PageIndex: 1,
          State: "在职",
        };

        if (isStaffNo) {
          searchParams.StaffNo = query;
        } else {
          searchParams.Name = query;
        }

        const response = await api.searchPersons(searchParams);
        if (response.Code !== 200 || !response.Data) {
          return [];
        }

        return response.Data.map((person: any) => ({
          value: person.ID,
          text: person.Name,
          subtitle: `工号: ${person.StaffNo}${
            person.GroupName ? ` | ${person.GroupName}` : ""
          }`,
        }));
      } catch (error) {
        return [];
      }
    },
  },
  {
    key: "originalGroupId",
    label: "原部门",
    type: "department-picker",
    placeholder: "请选择原部门",
    popupTitle: "选择部门",
    departmentData: [], // 将在页面加载时动态填充
  },
  {
    key: "newGroupId",
    label: "新部门",
    type: "department-picker",
    placeholder: "请选择新部门",
    popupTitle: "选择部门",
    departmentData: [], // 将在页面加载时动态填充
  },
  {
    key: "billCode",
    label: "单据编号",
    placeholder: "请输入单据编号",
  },
  {
    key: "applyDate",
    label: "申请日期",
    type: "daterange",
    placeholder: "请选择申请日期范围",
  },
  {
    key: "billStatus",
    label: "单据状态",
    type: "selector",
    placeholder: "请选择单据状态",
    options: ["草稿", "正文"],
  },
  {
    key: "newPositionId",
    label: "新岗位",
    placeholder: "请输入新岗位",
  },
  {
    key: "workflowStatus",
    label: "工作流状态",
    type: "selector",
    placeholder: "请选择工作流状态",
    options: ["待提交", "提交中", "审核中", "已完成", "已取消"],
  },
];

// 定义操作按钮
const actions = [
  {
    key: "delete",
    label: "删除",
    icon: "trash",
    color: "#FF5252",
    class: "delete-btn",
  },
  {
    key: "edit",
    label: "编辑",
    icon: "compose",
    color: "#4CAF50",
    class: "edit-btn",
  },
  {
    key: "view",
    label: "查看",
    icon: "eye",
    color: "#7881de",
    class: "view-btn",
  },
];

// 调岗调薪申请列表数据
const transferList = ref<ISysHrTransferRequestBillView[]>([]);

// 部门数据缓存（用于名称和ID的转换）
const departmentDataCache = ref<any[]>([]);

// 删除调岗调薪申请
const handleDelete = async (item: ISysHrTransferRequestBillView) => {
  try {
    // 调用删除API，传入ID数组
    await api.delete([item.ID!]);

    // 显示成功提示
    uni.showToast({
      title: "删除成功",
      icon: "success",
      duration: 1500,
    });
  } catch (error) {
    // 显示错误提示
    uni.showToast({
      title: "删除失败，请稍后重试",
      icon: "none",
      duration: 2000,
    });
  }
};

// 处理筛选
const handleFilter = async (filterParams: Record<string, any>) => {
  loading.value = true;
  try {
    // 构建查询参数，映射到API接口需要的字段
    const queryParams: ISysHrTransferRequestBillQuery = {
      Limit: 9999, // 一次性获取所有数据
      Page: 1,
    };

    // 根据筛选参数构建查询对象
    if (filterParams.personId) {
      queryParams.PersonId = filterParams.personId;
    }
    if (filterParams.originalGroupId) {
      queryParams.OriginalGroupId = filterParams.originalGroupId;
    }
    if (filterParams.newGroupId) {
      queryParams.NewGroupId = filterParams.newGroupId;
    }
    if (filterParams.newPositionId) {
      queryParams.NewPositionId = filterParams.newPositionId;
    }
    // 处理申请日期范围：确保结束日期包含当天的所有时间
    const applyDateRange = processDateRangeField(filterParams, "applyDate");
    if (applyDateRange) {
      queryParams.ApplyDate = applyDateRange;
    }
    if (filterParams.billCode) {
      queryParams.BillCode = filterParams.billCode;
    }
    if (filterParams.billStatus) {
      // 直接使用字符串文字
      queryParams.BillStatus = filterParams.billStatus;
    }
    if (filterParams.workflowStatus) {
      // 直接传递文字，不转换为数字
      queryParams.WorkflowStatus = filterParams.workflowStatus;
    }

    const response = await api.search(queryParams);

    if (response && response.Data) {
      transferList.value = response.Data;
    } else {
      transferList.value = [];
    }
  } catch (error) {
    transferList.value = [];

    // 显示错误提示
    uni.showToast({
      title: "筛选搜索失败，请稍后重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    loading.value = false;
  }
};

// 静默刷新数据获取函数（供XenListPage组件调用）
const silentRefreshFn = async () => {
  const response = await api.search({
    Limit: 9999, // 一次性获取所有数据
    Page: 1,
  });
  return response?.Data || [];
};

// 处理静默刷新结果
const handleSilentRefresh = (newData: ISysHrTransferRequestBillView[]) => {
  transferList.value = newData;
};

// 处理刷新事件
const handleRefresh = () => {
  // 只有在首次加载或明确需要刷新时才调用fetchData
  if (transferList.value.length === 0) {
    fetchData();
  }
};

// 加载状态
const loading = ref(false);

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const response = await api.search({
      Limit: 9999, // 一次性获取所有数据
      Page: 1,
    });

    if (response && response.Data) {
      transferList.value = response.Data;
    } else {
      transferList.value = [];
    }
  } catch (error) {
    transferList.value = [];

    // 显示错误提示
    uni.showToast({
      title: "获取调岗调薪信息失败，请稍后重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    loading.value = false;
  }
};

// 加载部门数据
const loadDepartmentData = async () => {
  try {
    const response = await commonApiInstance.GetParentsTree(false);
    if (response && Array.isArray(response)) {
      // 缓存部门数据
      departmentDataCache.value = response;

      // 找到部门筛选字段并更新其部门数据
      const originalDepartmentField = filterFields.find(
        (field) => field.key === "originalGroupId",
      );
      if (originalDepartmentField) {
        originalDepartmentField.departmentData = response;
      }

      const newDepartmentField = filterFields.find(
        (field) => field.key === "newGroupId",
      );
      if (newDepartmentField) {
        newDepartmentField.departmentData = response;
      }
    }
  } catch (error) {}
};

// 页面加载
onMounted(async () => {
  await loadDepartmentData();
  fetchData();
});
</script>
